package ch.fusun.baron.treasury.ui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.menus.WorkbenchWindowControlContribution;

import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.core.injection.ReInjector;
import ch.fusun.baron.core.service.UserService;
import ch.fusun.baron.data.DataListener;
import ch.fusun.baron.data.DataUpdate;
import ch.fusun.baron.player.Dynasty;
import ch.fusun.baron.player.api.PlayerService;
import ch.fusun.baron.treasury.api.TreasuryService;

/**
 * Shows the treasury of the current player in the task bar
 */
public class TreasuryContribution extends WorkbenchWindowControlContribution
		implements DataListener {

	@Inject
	private transient TreasuryService treasuryService;

	@Inject
	private transient PlayerService playerService;

	@Inject
	private transient UserService userService;

	private transient Label text;

	/**
	 * 
	 */
	public TreasuryContribution() {
	}

	/**
	 * @param id
	 */
	public TreasuryContribution(String id) {
		super(id);
	}

	@Override
	protected Control createControl(Composite parent) {
		ReInjector.getInstance().reInject(this);
		text = new Label(parent, SWT.NONE);
		text.setText("                  "); //$NON-NLS-1$
		treasuryService.addDataListener(this);
		return text;
	}

	@Override
	public void dataChanged(DataUpdate update) {
		if (!text.isDisposed()) {
			text.getDisplay().asyncExec(new Runnable() {

				@Override
				public void run() {
					Dynasty dynasty = playerService.getDynasty(userService
							.getUser());
					if (dynasty != null) {
						text.setText("" //$NON-NLS-1$
								+ treasuryService.getMoney(dynasty));
					}
				}
			});
		}
	}
}
